﻿/*!
 * LightSO.NET JavaScript Library for Easyui MVC v1.0.0
 * http://www.easymvc.com/
 * Include: jQuery & Easyui & syExtEasyUI
 * Author: Rocky Lin
 * Date: 2015-02-10
 */
(function (window, undefined) {

    //定义本地变量初始化easymvc库
    var // Define a local copy of easymvc
    //确保options默认值
    setupOptions = function (options) {
        //定义默认参数
        var opt = {
            grid: '',               //datagrid对象或datagrid的id
            url: "",                //请求的链接
            data: null,             //传入数据
            callback: null,         //成功之后要做的事情
            form: null,             //提交的表单对象
            buttons: [],            //自定义easyui按钮数组(用于弹框)
            width: 'auto',          //默认宽度
            height: 480,            //默认高度
            iconCls: 'icon-add',    //默认图标
            title: 'Alert',         //默认标题
            msg: '',                //默认消息
            singleSelect: true      //是否单选（弹框时如果传入grid参数，则会检查该选项）
           
        };

        return $.extend(true, {}, opt, options);
    },
    logic = {}, datagridCache = null, treegridCache = null,
    easymvc = function (extendName) { //easymvc库构造函数

        if (!this.popupMenu)
            this.popupMenu = null;

        var name = (!extendName ? '' : extendName.toLowerCase());

        if (!logic[name])
            logic[name] = this;

        return this;
    },
    attach = function (obj, name, fn) {
        obj[name] = function (param0, param1, param2, param3, param4, param5, param6) {
            return fn.call(obj, param0, param1, param2, param3, param4, param5, param6);
        };
    };

    easymvc.fn = easymvc.prototype = {};

    /********************* 定义easymvc.js公共方法 ************************/

    //add by rocky on 20150204: 切换panels
    //btn: group中选中的按钮jquery对象，如：$('#btnTest')
    //showId：将要显示panel的id值
    //panelIds：参与切换的所有panel的id值
    easymvc.fn.togglePanels = function (btn, showId, panelIds, isRadio, useJavascript) {

        if (!isRadio) { //表示为按钮类型，非单选
            if ($(btn).linkbutton('options').selected)
                return;
        }

        $(panelIds).each(function () {
            $('#' + this).hide();
        });

        $('#' + showId).show().panel();

        if (useJavascript)
            window.easymvc.use(useJavascript);
    };

    /*************  Treegrid ***********************/
    //add by baddy on 20150313: 初始化treegrid
    //id: Treegrid的Id，如果是嵌的tab panel中的Treegrid，指向的是panel中的Treegrid的Id
    //url: 指的是Treegrid加载数据的请求地址
    //onDblClickRow: 可选项，双击一行时执行的脚本
    easymvc.fn.createTreegrid = function (id, url) {

        if (!treegridCache)
            treegridCache = new Array();

        //再次显示表格时直接返回缓存的表格不再初始化第二次
        if (treegridCache[id])
            return treegridCache[id];

        
        var singleSelect = /singleSelect:true/gmi.test($('#' + id).attr('data-options'));
        var columns = eval('columns_' + id);
        if (!singleSelect && columns && $(columns).size() && columns[0] && $(columns[0]).size()) {
            columns[0].splice(0, 0, { field: 'checkall', title: '<input id=\"chk_' + id + '\" type=\"checkbox\"  >', width: 30, checkbox: true });
        }

        var onClickRowEvent = eval('(typeof (onClickRowEvent_' + id + ') == "undefined" ? function(){} : onClickRowEvent_' + id + ')');
        var onDblClickRowEvent = eval('(typeof (onDblClickRowEvent_' + id + ') == "undefined" ? function(){} : onDblClickRowEvent_' + id + ')');
        
        var treegrid = $('#' + id).treegrid({
            url: url,
            method: 'POST',
            toolbar: "#treegrid_toolbar_" + id,
            striped: true,
            animate: true,
            collapsible: true,
            onClickRow: function (index, row) {
                onClickRowEvent(index, row);
            },
            fit: true,
            nowrap: false,
            width: 'auto',
            height: "auto",
            rownumbers: true,
            fitColumns: false,
            border: false,
            idField: 'Id',
            treeField: 'Name',
            loadMsg: 'Processing, please wait ...',
            columns: columns,
            onLoadError: function (data) {
                if (data.responseText.indexOf('<title>登录</title>') > -1)
                    window.location.href = '/home/login?ReturnUrl=' + window.location.href; //window.top.window.location.href = '/';
                else
                    window.easymvc.message({ title: '出错了', msg: data.statusText });
            },
            onLoadSuccess: function (row, data) {
                var node = $(this).treegrid('getSelected');
                if (node) {
                    $(this).treegrid('select', node.Id);
                    $(this).treegrid('expand', node.Id);
                    $(this).treegrid('expandTo', node.Id);
                }
            },
            onDblClickRow: onDblClickRowEvent,
            loadFilter: function (data) {
                if (data.IsSuccess) {
                    return data.Data
                } else {
                    return [];
                }
            },
            rowStyler: function (row) {
                if (row.Status != 0) {
                    return 'color:gray;';
                } else if (row.Sensitive)
                    return 'color:red';
            },
            //行右键显示操作菜单
            onContextMenu: function (e, row) {
                e.preventDefault();
                $(this).treegrid('select', row.Id);
                $('#popupmenu_' + id).menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        });

        if (treegrid) { //将已初始化的treegrid缓存起来
            treegridCache[id] = treegrid;
            window.easymvc.cache(id, treegrid); //跨域使用
        }

        return treegrid;
    };

    //表格数据刷新
    //treegridId: treegrid的id
    easymvc.fn.treegridReload = function (id,node) {
        if (!window.easymvc.cache(id))
            return;

        window.easymvc.cache(id).treegrid("reload");
    };
    /************   Treegrid end ************************/

    /***************************************** Datagrid begin ********************************************************/
    //add by rocky on 20150203: 初始化Datagrid
    //id: Datagrid的Id，如果是嵌的tab panel中的Datagrid，指向的是panel中的Datagrid的Id
    //url: 指的是Datagrid加载数据的请求地址
    //onDblClickRow: 可选项，双击一行时执行的脚本
    easymvc.fn.createDatagrid = function (id, url, opts) {

        if (!datagridCache)
            datagridCache = new Array();

        //再次显示表格时直接返回缓存的表格不再初始化第二次
        if (datagridCache[id])
            return datagridCache[id];

        var singleSelect = /singleSelect:true/gmi.test($('#' + id).attr('data-options'));
        var columns = eval('columns_' + id);
        if (!singleSelect && columns && $(columns).size() && columns[0] && $(columns[0]).size()) {
            columns[0].splice(0, 0, { field: 'checkall', title: '<input id=\"chk_' + id + '\" type=\"checkbox\"  >', width: 30, checkbox: true });
        }

        var rowStyler = eval('(typeof (rowStyler_' + id + ') == "undefined" ? function(){ return "";} : rowStyler_' + id + ')');
        var onClickRowEvent = eval('(typeof (onClickRowEvent_' + id + ') == "undefined" ? function(){} : onClickRowEvent_' + id + ')');
        var onDblClickRowEvent = eval('(typeof (onDblClickRowEvent_' + id + ') == "undefined" ? function(){} : onDblClickRowEvent_' + id + ')');

        var datagrid = $('#' + id).datagrid({
            url: url,
            method: 'POST',
            toolbar: "#datagrid_toolbar_" + id,
            fit: true,
            showHeader: (opts && (typeof (opts.showHeader) != "undefined" && opts.showHeader != null) ? opts.showHeader : true),
            checkOnSelect: true,
            selectOnCheck: true,
            onClickRow: function (index, row) {
                onClickRowEvent(index, row);
            },
            rowStyler: function (index, row) {
                return rowStyler(index, row);
            },
            nowrap: false,
            width: 'auto',
            height: "auto",
            rownumbers: true,
            showFooter:true,
            fitColumns: false,
            pageSize: (opts && opts.pageSize ? opts.pageSize : 30),
            pageNumber: 1,
            border: false,
            pageList: [20, 30, 40, 50],
            pagination: (opts && (typeof (opts.pagination) != "undefined" && opts.pagination != null) ? opts.pagination : true),
            queryParams: {  },
            columns: columns,
            onLoadError: function (data) {
                if (data.responseText.indexOf('<title>登录</title>') > -1)
                    window.location.href = '/home/login?ReturnUrl=' + window.location.href; //window.top.window.location.href = '/';
                else
                    window.easymvc.message({ title: '出错了', msg: data.statusText });
            },
            onLoadSuccess: function (data) {
                if (!data.IsSuccess && typeof (data.IsSuccess) != "undefined") {
                    if (data.responseText && data.responseText.indexOf('<title>登录</title>') > -1)
                        window.location.href = '/home/login?ReturnUrl=' + window.location.href; //window.top.window.location.href = '/';
                    else
                        window.easymvc.message({ title: '出错了', msg: data.Message });
                }
                else //控制表格内容不能被选中
                    $("table[id='" + id + "']").parent(".datagrid-view").attr("onselectstart", "return false").css({ "-moz-user-select": "none" });
            },
            onDblClickRow: onDblClickRowEvent,
            loadFilter: function (data) {
                if (data.rows) {
                    return data
                } else {
                    data.rows = [];
                    return data;
                }
            },
            remoteSort: true,
            enableHeaderClickMenu: true,        //此属性开启表头列名称右侧那个箭头形状的鼠标左键点击菜单
            enableHeaderContextMenu: true,      //此属性开启表头列名称右键点击菜单
            enableRowContextMenu: false,
            //行右键显示操作菜单
            onRowContextMenu: function (e, rowIndex, rowData) {
                e.preventDefault();
                $(this).datagrid('selectRow', rowIndex);
                $('#popupmenu_' + id).menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        });

        if (datagrid) { //将已初始化的datagrid缓存起来
            datagridCache[id] = datagrid;
            window.easymvc.cache(id, datagrid); //跨域使用
        }

        return datagrid;
    };

    //datagrid panel上的搜索按钮的search方法
    easymvc.fn.search = function (value, name) {
        window.easymvc.query($("#_GridId").val(), $("#_FormId").val());
    };

    //datagrid panel上的搜索框回车后的search方法
    easymvc.fn.query = function (gridID, formId, fn) {
        var queryParams = $('#' + gridID).datagrid('options').queryParams;

        var formDom = window.easymvc.getForm(formId);
        if (!formDom[0])
            formDom = $("#" + formId);

        var formValues = this.serializeJson(formDom);

        formDom.find("[name]").each(function (i, n) {
            var name = $(n).attr("name");
            queryParams[name] = formValues[name] == 'on' ? true : formValues[name];
            if ($(n).attr("class") && $(n).attr("class").indexOf("searchbox") > -1) {
                queryParams[name] = formDom.find("[searchboxname='" + name + "']").searchbox("getValue");
            }
        });

        queryParams["page"] = 1;
        queryParams["PageIndex"] = 1;
        //重新加载datagrid的数据  
        $('#' + gridID).datagrid('reload');
    };
    
    //清空查询条件
    easymvc.fn.clear = function (gridID, formId) {
        $("#" + formId + " input[unclear!='true']").val("");
        $("#" + formId + " .easyui-combobox").combobox("setValue", -100); //清空默认将选择项恢复到原始值
        $("#" + formId + " .easyui-combotree").combotree("clear"); //清空默认将选择项恢复到原始值

        //查找数组值里面是否存在小于0的，没有的话，则设置默认值为第一项
        $("#" + formId + " .easyui-combobox").each(function (i, n) {
            var comboData = $(n).combobox("getData");
            var list = $.grep(comboData, function (n, i) {
                return n.value < 0;
            });
            if (!list || list.length <= 0)
                $(n).combobox("setValue", comboData[0].value);
        });

        $("#" + formId + " [searchboxname]").searchbox("setValue", "");
        this.query(gridID, formId);
    };

    //数据表格右键点击创建可自由控制列显示或者隐藏
    easymvc.fn.createColumnMenu = function (dg) {
        if (!dg || !$('#' + dg)[0]) return;

        var m = $('<div/>').appendTo('body');
        m.menu({
            onClick: function (item) {
                if (item.iconCls == 'icon-ok') {
                    $('#' + dg).datagrid('hideColumn', item.name);
                    m.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    $('#' + dg).datagrid('showColumn', item.name);
                    m.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
        var fields = $('#' + dg).datagrid('getColumnFields');
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var col = $('#' + dg).datagrid('getColumnOption', field);
            m.menu('appendItem', {
                text: col.title,
                name: field,
                iconCls: 'icon-ok'
            });
        }
        this.popupMenu = m;
    };
    /********************************************************** Datagrid end *******************************************/

    //浏览器缓存方法
    easymvc.fn.cache = function (key, data) {

        if (!top.localCache)
            top.localCache = {};

        if (!data)
            return top.localCache[key];

        return (top.localCache[key] = data);
    };

    //公用的异步调用数据
    easymvc.fn.ajax = function (options) {
        //确保参数有默认值
        options = setupOptions(options);
        if (options.url && $.trim(options.url).length > 0)
            $.ajax({
                type: "POST",
                url: options.url,
                data: options.data,
                cache: false,
                dataType: "json",
                async: true,
                success: function (result) {
                    if (!result.IsSuccess) {
                        if (result.Message)
                            window.easymvc.message({ title: "出错啦", msg: result.Message });
                        if (result.VaildList && result.VaildList.length > 0) {
                            var s = "";
                            $(result.VaildList).each(function (i, n) {
                                s += "<div>" + n.Message + "</div>";
                            });
                            window.easymvc.message({ title: "出错啦", msg: s, height: 'auto' });
                        }
                    } else {

                        //成功之后要做的事情(参数可选)
                        if (options.callback && typeof (options.callback) == "function")
                            options.callback.call(options, result);

                        //用于ajax, 删除处理，有传入 grid（指的是Id）,就进行表格删除处理, 不再在外面进行处理
                        if (options.grid != null && $.trim(options.grid) != "" && typeof (options.grid) != "undefined" && typeof (options.grid) == "string") { //且为表格删除
                            var isTreegrid = $("#treegrid_toolbar_" + options.grid).size() > 0;
                            var rows = 0;
                            if (isTreegrid)
                                rows = $("#" + options.grid).treegrid("getSelections"); //获得选中的行
                            else
                                rows = $("#" + options.grid).datagrid("getSelections"); //获得选中的行

                            if (rows) { //判断不为空
                                $(rows).each(function (i, n) { //循环行获得行索引,进行删除
                                    if (isTreegrid) {
                                        $("#" + options.grid).treegrid("remove", n.Id); //删除
                                    } else {
                                        var index = $("#" + options.grid).datagrid("getRowIndex", n); //行索引
                                        $("#" + options.grid).datagrid("deleteRow", index); //删除
                                    }
                                });
                            }
                        }

                        //弹框提示
                        if (!options.dontAlert)
                            window.easymvc.message({ title: "成功", msg: (!result.Message ? '操作成功！' : result.Message) });
                    }
                },
                complete: function (XHR, TS) {
                    if (XHR.responseText.indexOf("<title>登录</title>") > -1)
                        window.location.href = '/home/login?ReturnUrl=' + window.location.href;
                        //window.easymvc.dialog({ width: '800', height: '600', url: '/home/login', title: '登录超时,重新登录', buttons: null });
                },
                error: function (XHR, textStatus, errorThrown) {
                    if (XHR.responseText.indexOf("<title>登录</title>") > -1)
                        window.location.href = '/home/login?ReturnUrl=' + window.location.href;
                    else
                        window.easymvc.message({ title: "错误", msg: errorThrown });
                }
            });
    };

    //公用的form提交
    easymvc.fn.submit = function (options) {
        //确保参数有默认值
        options = setupOptions(options);

        //传入的是form id时，获取id指定的对象 (form参数可传id也可传对象)
        if (typeof (options.form) == 'string') {
            options.form = options.dialog.form;
        }

        $(options.form).form('submit', {
            url: options.url,
            onSubmit: function (param) {
                //var isValid = $(this).form('validate');
                //return isValid;

                var isValid = $(this).find(".validatebox-invalid")[0] ? false : true;
                if (!isValid) {
                    if (options.dialog.find('iframe')[0])
                        window.easymvc.backPosition($(this), $(options.dialog.find('iframe').get(0).contentWindow.document));
                    else
                        window.easymvc.backPosition($(this));
                }
                return isValid;
            },
            success: function (result) {
                if (typeof (result) == 'string' && /\{[\w\W]+\}/.test(result))
                    result = eval('(' + result + ')');
                else {
                    if (result.indexOf('<form id="frmLogin" method="post" action="/home/login">') > -1) {
                        var dialog_self = $(options.form).data("dialog_self");
                        var dialog_self_id = $("input.dialog_self_id").val();
                        if (dialog_self) {
                            dialog_self.dialog('destroy');
                        }
                        if (dialog_self_id) {
                            $(parent.document).find("#" + dialog_self_id).parent().next().next().remove();
                            $(parent.document).find("#" + dialog_self_id).parent().next().remove();
                            $(parent.document).find("#" + dialog_self_id).parent().remove();
                        }
                        window.location.href = '/home/login?ReturnUrl=' + window.location.href;
                    }
                    else
                        window.easymvc.message({ title: "出错啦", msg: result, height: 'auto' });
                    return;
                }
                if (!result.IsSuccess) {
                    if (result.Message)
                        window.easymvc.message({ title: "出错啦", msg: result.Message });
                    if (result.VaildList && result.VaildList.length > 0) {
                        var s = "<div style='color:red;'>带(*)号为必填项</div><div style='color:red;'>请填写完整</div><div style='color:red;'>保持格式正确</div>";
                        $(result.VaildList).each(function (i, n) {
                            s += "<div>" + n.Message + "</div>";
                        });
                        window.easymvc.message({ title: "出错啦", msg: s, height: 'auto' });
                    }
                }
                else {
                    //成功之后要做的事情(带返回参数)
                    if (options.callback && typeof (options.callback) == "function")
                        options.callback.call(options, result);

                    //update by rocky: 如果有弹框应该在callback处理
                    //如果有弹框,关闭弹框
                    if (options.dialog)
                        options.dialog.dialog('destroy');
                    if (options.grid) {
                        var isTreegrid = $("#treegrid_toolbar_" + options.grid).size() > 0;
                        if (isTreegrid) {                          
                            $("#" + options.grid).treegrid('reload');
                        }
                        else
                            window.easymvc.datagridReload(options.grid);
                    }

                    window.easymvc.message({ title: "成功", msg: (!result.Message ? '保存成功！' : result.Message) });
                }
            }
        });
    };


    //公共弹框
    easymvc.fn.dialog = function (options) {

        //确保参数有默认值
        options = setupOptions(options);

        if (typeof (options.grid) == 'string')
            options.grid = $('#' + options.grid);

        //参数传入表格时，要求有选中行才显示对话框
        if (options.grid && options.grid.size() > 0) {
            var rows = options.grid.datagrid("getSelections");
            if (!rows || $(rows).size() < 1) {
                window.easymvc.message({ title: "提示", msg: "请选择一条记录" });
                return false;
            }
            //检查是否允许多选
            if (options.singleSelect && $(rows).size() > 1) {
                window.easymvc.message({ title: "提示", msg: "不能选取多条记录" });
                return false;
            }
        }

        //传入的是form对象时，获取id值 (form参数可传id也可传对象)
        if (options.form && options.form.length && typeof (options.form) != 'string' && $(options.form).hasAttr('id'))
            options.form = options.form.id;


        var formDom = $('#' + options.form);
        //定义默认按钮
        var buttons = [{
            text: '取消',
            iconCls: 'icon-cancel',
            handler: function () {
                dialog.dialog('destroy');
            }
        }];

        //重新处理按钮的回调函数以简化调用时必须的操作
        if (options.buttons && options.buttons.length != undefined && options.buttons.length > 0) {
            $(options.buttons).each(function (i, btn) {
                if (btn.handler) {
                    //回调函数
                    if (btn.handler && typeof (btn.handler) == "function") {
                        btn.fn = btn.handler; //存起用户定义的函数以备调用
                        btn.handler = function () {
                            clickEvent(btn, formDom);
                        };
                    }
                }

                buttons.splice(btn.num, 0, btn);
            });
        }

        //查找表单为显示内容，没有表单时显示url指定的模版
        var content = options.form ? $('<form method="post" />').attr('id', "dlg_" + formDom.attr("id")).append(formDom.html()) : null;

        if (content) { //确保表单显示状态
            content.find('form').show();
        } else if (!options.url) {//没有表单也没有url时，显示msg
            content = $('<p />').css({ paddingLeft: 10, paddingRight: 10 }).text(options.msg);
        }

        options.id = options.id ? options.id : (options.url ? options.url.replace(/[\/|=|?|&]/gm, '') : 'random_' + Math.random().toString().replace("0.", ""));

        var dialog = parent.sy.modalDialog({
            id: options.id,
            title: options.title,
            iconCls: options.iconCls,
            url: options.form ? null : options.url,
            content: content,
            width: options.width,
            height: options.height,
            buttons: buttons,
            resizable: true,
            maximizable: (options.maximizable == undefined ? true : options.maximizable)
        });

        if (content)
            $(content).find("[class*='easyui-']").each(function (i, n) {
                var cls = $(n).attr("class");
                var ncls = $(n).next().attr("class");
                var nncls = $(n).next().next().attr("class");
                if (ncls == nncls && cls.indexOf(nncls) > -1) {
                    $(n).next().find(".combo-text").attr("style", $(n).next().next().find(".combo-text").attr("style"));
                    $(n).next().find(".combo-arrow").attr("style", $(n).next().next().find(".combo-arrow").attr("style"));
                    $(n).next().next().remove();
                }
            });

        if (typeof (options.loadcallback) == "function")
            $(function () { options.loadcallback(); });

        $(content).data("dialog_self_id", options.id).data("dialog_self", dialog);
        $("body").append($("<input/>").attr("type", "hidden").attr("class", "dialog_self_id").val(options.id));
        //初始化
        $Init($(content));

        //点击按钮触发事件
        var clickEvent = function (btn, formDom) {

            if (dialog.find('iframe')[0])
                formDom = $(dialog.find('iframe').get(0).contentWindow.document).find('form');
            else
                formDom = $(dialog).find('form');

            var result = false;
            if (btn.fn) {    //存在用户定义的函数时执行

                var close = function () {
                    dialog.dialog('destroy');
                };
                //将对话框当参数提供给用户定义函数
                //用户定义函数中可通过this关键字访问dialog，通过this.button可以获取当前按钮，通过this.form可访问dialog中的表单，能过this.close()可关闭对话框
                if (dialog) {
                    dialog.button = btn;
                    dialog.form = formDom;
                    dialog.close = close;
                } else {
                    dialog = { button: btn, form: formDom, close: close };
                }
                result = btn.fn.call(dialog);
            }
            if (!btn.handler || result) {
                close();
                window.easymvc.message({ title: "成功", msg: "保存成功！" });
            }
        };

        //附加方法，可在返回的dialog对象调用form返回表单
        attach(dialog, 'getForm', function (id) {
            var form = window.easymvc.getForm(id, $(this));

            //附加方法，可在返回的form对象调用combo获取或设置iframe里的combobox值
            attach(form, 'combo', function (cmd, id, value) {
                if (cmd == 'setValue') {
                    var item = form.find('#' + id + ' [value=' + value + ']');
                    if (item && item[0]) {
                        form.find('#' + id).next().find('.combo-value').val(item.val()); //设置隐藏域值
                        form.find('#' + id).next().find('.validatebox-text').val(item.text()) //设置显示名称
                    }

                } else if (cmd == 'getValue') {
                    return form.find('#' + id).next().find('.combo-value').val() //返回值
                } else if (cmd == 'getName') {
                    return form.find('#' + id).next().find('.validatebox-text').val() //返回显示名称
                }
            });

            return form;
        });

        return dialog; 
    };

    //在弹框对象获得当前活动页Tab整个document
    easymvc.fn.tabDom = function (index) {
        var tDom = $(top.window.document).find("iframe").get(index).contentWindow.document;
        return $(tDom);
    };

    //公共弹框,获取表单Json对象
    easymvc.fn.jsonForm = function (id) {
        var f = $(top.window.document).find("#dlg_" + id);
        return this.serializeJson(f);
    };

    //公共弹框,获取表单对象
    easymvc.fn.getForm = function (id, dialog) {
        var f = $(top.window.document).find("#dlg_" + id);
        if (!f[0]) {
            if (dialog) {
                if (dialog.find('iframe')[0])
                    f = $(dialog.find('iframe').get(0).contentWindow.document).find('#' + id);
                else
                    f = $(dialog).find("#dlg_" + id);
            }
        }

        if (!f[0]) {
            if (id) {
                if (typeof (id) == typeof (0))
                    f = $(top.window.document).find("form")[id];
                //else
                //    f = $(top.window.document).find("#dlg_" + id);
            } else {
                f = $(top.window.document).find("form").first();
            }
        }

        return f;
    };

    //工作弹框，设置表单值，data为json复合对象（inuput控件的name:value）
    easymvc.fn.setForm = function (id, dialog, data, isedit) {
        var formCol = window.easymvc.getForm(id, dialog);
        if (data)
            $.each(data, function (name, value) {
                var col = formCol.find("[name='" + name + "']");
                if (col[0]) {
                    if (col[0].nodeName == "INPUT" || col[0].nodeName == "SELECT") {

                        if (col.size() == 1 && col.attr("type") == "checkbox") {
                            if (typeof (value) == "boolean") {
                                if (value.toString() == col.attr("value"))
                                    col.attr("checked", true);
                            } else {
                                if (value == col.attr("value"))
                                    col.attr("checked", true);
                            }
                        } else if (col.attr("type") == "radio") {
                            formCol.find("[name='" + name + "'][value='" + value + "']").attr("checked", true);
                        } else {
                            var dateRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}/
                            if (dateRegExp.test(value)) {
                                col.val(value.replace(' 00:00:00', ''));
                            } else {
                                col.val(value);
                            }
                        }
                    }
                    else if (col[0].nodeName == "TEXTAREA") {
                        col.text(value);
                    }
                    
                    if (isedit && col.hasClass("easyui-validatebox"))
                        col.removeClass("validatebox-invalid");
                }
            });
    };


    //表格数据刷新
    //datagridId: datagrid的id
    easymvc.fn.datagridReload = function (id) {
        if (!window.easymvc.cache(id))
            return;

        window.easymvc.cache(id).datagrid("reload");
    };

    //操作需确认弹框,多个用逗号，隔开
    easymvc.fn.confirm = function (options) {

        //确保参数有默认值
        options = setupOptions(options);

        if (typeof (options.grid) == 'string')
            options.grid = $('#' + options.grid);

        //参数传入表格时，要求有选中行才显示对话框
        if (options.grid && options.grid.size() > 0) {
            var rows = options.grid.datagrid("getSelections");
            if (!rows || $(rows).size() < 1) {
                window.easymvc.message({ title: "提示", msg: "请选择一条记录" });
                return false;
            }
            ////检查是否允许多选
            //if (options.singleSelect && $(rows).size() > 1) {
            //    window.easymvc.message({ title: "提示", msg: "不能选取多条记录" });
            //    return false;
            //}
        }

        parent.$.messager.confirm(options.title || '提示', options.msg, function (r) {
            if (!r) return; //如果按下取消按钮则直接返回掉

            //执行回调函数
            if (options.callback && typeof (options.callback) == "function")
                options.callback.call(options.grid, rows);//将表格选中的行作为参数返回
        });
    };


    //显示消息
    //title: 标题
    //msg: 消息内容
    //icon: 图标
    easymvc.fn.message = function (options) {
        parent.$.messager.show({ title: options.title, msg: options.msg, icon: options.icon, width: options.width, height: options.height, position: "bottomRight" });
    };


    //获取弹出框默认按钮组
    easymvc.fn.getDefaultButtons = function (options) {
        return [{
            num: 0,
            id: (options && options.id ? options.id : ""),
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                if (options.callback && typeof (options.callback) == "function")
                    options.callback();
            }
        }]
    };

    //easymvc库逻辑扩展
    //name: 扩展名称
    //fn: 功能函数对象（json或能返回json的方法）
    easymvc.fn.extend = function (name, fn) {

        if (!name)
            return;

        name = name.toLowerCase();
        var ret = function (data) {
            if (data && $.isPlainObject(data) && !$.isEmptyObject(data)) {
                if (!logic[name]) {
                    logic[name] = new easymvc(name);
                }
                $.extend(true, logic[name], data);
                window.easymvc = logic[name];
            }

            return logic[name];
        };

        if ($.isFunction(fn))
            fn = fn();

        return ret(fn);;
    };


    //选择使用逻辑扩展库
    //name: 扩展名称
    easymvc.fn.use = function (name) {

        if (!name)
            return;

        if (!logic[name.toLowerCase()])
            window.easymvc = logic[''];
        else
            window.easymvc = logic[name.toLowerCase()];

        return window.easymvc;
    };

    //动态加载js,css
    easymvc.fn.loadjscssfile = function (filename, filetype) {

        if (filetype == "js") {
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("charset", "utf-8");
            fileref.setAttribute("src", filename);
        } else if (filetype == "css") {

            var fileref = document.createElement('link');
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }
        if (typeof fileref != "undefined") {
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
    };

    //form序列化
    easymvc.fn.serializeJson = function (form) {
        var serializeObj = {};

        $(form.serializeArray()).each(function () {
            serializeObj[this.name] = this.value.replace(/['"]/gm, '"').replace(/</gm, '&lt;').replace(/>/gm, '&gt;');
        });
        var radioCol = $(form).find("input:radio");
        if (radioCol[0]) {
            $(radioCol).each(function () {
                if (serializeObj[this.name] == undefined || serializeObj[this.name] == null)
                    serializeObj[this.name] = "";
            });
        }
        return serializeObj;
    };

    //获得编号
    easymvc.fn.getCode = function (id, codetype) {

        var codeLength = 6;//流水号长度暂时定位6
        //假如Id为0的话,则返回空
        if (id == 0) {
            return "";
        }

        //将编号补充0至足够的位数
        var l = codeLength - id.toString().length;
        var s = "";
        for (var i = 0; i < l; i++) {
            s += "0";
        }
        var str = s + id.toString();

        //计算checkDigit
        var checkDigit = 0;
        var x = codeLength;
        for (var i = 0; i < codeLength; i++) {
            checkDigit += x * Number(str.substring(i, i + 1));
            x--;
        }
        checkDigit = checkDigit % 10;

        var exp = new RegExp("^(\\d{3})(\\d{3})$", "g");
        return codetype + str.replace(exp, '$1' + checkDigit.toString() + '$2');
    };

    //当出现错误提示，则点击保存返回到错误位置
    easymvc.fn.backPosition = function ($this, $dom) {
        var validCol = $this.find(".easyui-validatebox");
        validCol = !validCol[0] ? $this : validCol[0];

        $dom = !$dom ? $(document) : $dom;
        $body = $dom.find("body");
        $html = $dom.find("html");

        if ($dom.scrollTop() > $this.offset().top) {
            if ($body.data("errorscroll") == undefined) {
                $body.data("errorscroll", 1);
                $body.animate({ "scrollTop": $this.offset().top + "px", "position": "static" }, 600);
                $html.animate({ "scrollTop": $this.offset().top + "px", "position": "static" }, 600);
            }
            setTimeout(function () {
                $body.removeData("errorscroll");
            }, 600);
        }
    };

    //当form出现checkbox多选的情况下
    easymvc.fn.setChkMultiValue = function (name, formId) {
        var formDom = $(document);
        var $this;
        if (formId) {
            formDom = window.easymvc.getForm(formId);
        }
        $this = formDom.find("input:hidden[name='" + name + "']");
        var c = formDom.find("input:checked[type='checkbox'][name='" + name + "_chk']");
        var str = new StringBuffer();
        $(c).each(function (i, n) {
            str.append($(n).val());
        });
        $this.val(str.toString(","));
    };

    //转换日期
    easymvc.fn.GetCovDate = function (d, formatstring) {
        if (!d) return '';
        if (!formatstring) formatstring = "yyyy-MM-dd";
        if (d.indexOf("/Date") > -1) {
            var nS = d.replace(/\/(Date\(-?\d+\))\//, '$1');
            eval('var covDate = new ' + nS + ';');
            return covDate.format(formatstring);
        } else {
            var date = eval('new Date(' + d.replace(/\d+(?=-[^-]+$)/,
            function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
            return date.format(formatstring);
        }
    };

    // 打开新窗口，防拦截
    easymvc.fn.openUrl = function (url, isself) {
        var f = document.createElement("form");
        f.setAttribute("action", url);
        f.setAttribute("method", 'post');
        if (isself == true)
            f.setAttribute("target", '_self');
        else
            f.setAttribute("target", '_blank');
        document.body.appendChild(f);
        f.submit();
    };

    //全局访问声明
    // If there is a window object, that at least has a document property,
    // define easymvc and $ identifiers
    if (typeof window === "object" && typeof window.document === "object") {
        window.easymvc = new easymvc();
    }

})(window);
